package com.tf.six.service.impl;

import com.tf.six.entity.Product1;
import com.tf.six.mapper.ProductMapper;
import com.tf.six.service.HotProductStatisticService;
import com.tf.six.util.RedisKeyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class HotProductStatisticServiceImpl implements HotProductStatisticService {//热门商品统计服务实现

    private final RedisTemplate<String, Object> redisTemplate;
    private final ProductMapper productMapper;

    @Autowired
    public HotProductStatisticServiceImpl(RedisTemplate<String, Object> redisTemplate,
                                          ProductMapper productMapper) {
        this.redisTemplate = redisTemplate;
        this.productMapper = productMapper;
    }

    @Override
    public List<Map<String, Object>> getHotProducts(int limit) {
        // 从Redis获取热门商品排行
        Set<ZSetOperations.TypedTuple<Object>> products = redisTemplate.opsForZSet()
                .reverseRangeWithScores(RedisKeyUtil.HOT_PRODUCT_KEY, 0, limit - 1);

        if (products == null || products.isEmpty()) {
            // 如果Redis中没有数据，从数据库获取并缓存
            return getHotProductsFromDB(limit);
        }

        return products.stream()
                .map(tuple -> {
                    Long productId = Long.valueOf(tuple.getValue().toString());
                    Product1 product = productMapper.selectById(productId);
                    if (product == null) {
                        return null;
                    }
                    Map<String, Object> map = new HashMap<>();
                    map.put("product", product);
                    map.put("score", tuple.getScore());
                    return map;
                })
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
    }

    private List<Map<String, Object>> getHotProductsFromDB(int limit) {
        // 从数据库获取热门商品（按浏览量降序）
        List<Product1> products = productMapper.selectList(null); // 实际项目中应该使用分页查询

        return products.stream()
                .sorted((p1, p2) -> Long.compare(p2.getViewCount(), p1.getViewCount()))
                .limit(limit)
                .map(product -> {
                    Map<String, Object> map = new HashMap<>();
                    map.put("product", product);
                    map.put("score", product.getViewCount());
                    // 将数据存入Redis
                    redisTemplate.opsForZSet().add(
                            RedisKeyUtil.HOT_PRODUCT_KEY,
                            product.getId().toString(),
                            product.getViewCount()
                    );
                    return map;
                })
                .collect(Collectors.toList());
    }

    @Override
    public void incrementProductViewCount(Long productId) {
        // Redis中增加商品浏览量
        redisTemplate.opsForZSet().incrementScore(
                RedisKeyUtil.HOT_PRODUCT_KEY,
                productId.toString(),
                1
        );

        // 增加商品在数据库中的浏览量
        Product1 product = productMapper.selectById(productId);
        if (product != null) {
            product.setViewCount(product.getViewCount() + 1);
            productMapper.updateById(product);
        }
    }

    @Override
    public Long getProductViewCount(Long productId) {
        // 从Redis获取商品浏览量
        Double score = redisTemplate.opsForZSet().score(
                RedisKeyUtil.HOT_PRODUCT_KEY,
                productId.toString()
        );

        if (score != null) {
            return score.longValue();
        }

        // 如果Redis中没有，从数据库获取
        Product1 product = productMapper.selectById(productId);
        return product != null ? product.getViewCount() : 0L;
    }
}
